package org.creavi.engine.hud.builder;

import org.creavi.engine.hud.HudDefinition;
import org.creavi.engine.hud.HudInstance;
import org.creavi.engine.texture.TextureFactory;

import com.jme.math.Vector2f;
import com.jme.renderer.Renderer;
import com.jme.scene.TexCoords;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.shape.Quad;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.geom.BufferUtils;

public abstract class HudInstanceBuilder {
	protected HudInstance hudInstance;

	public HudInstanceBuilder() {
	}

	public void createNewHudInstance(String name, HudDefinition hudDefinition) {
		hudInstance = new HudInstance(name, hudDefinition);
	}

	public HudInstance getHudInstance() {
		return hudInstance;
	}

	public void buildBasicHud(HudDefinition hudDefinition) {
		float width = hudDefinition.getWidth();
		float height = hudDefinition.getHeight();

		Quad quad = new Quad("hud", width, height);

		hudInstance.setWidth(width);
		hudInstance.setHeight(height);

		quad.setRenderQueueMode(Renderer.QUEUE_ORTHO);
		quad.setLightCombineMode(LightCombineMode.Off);
		quad.updateRenderState();

		hudInstance.getHudNode().attachChild(quad);
		hudInstance.setHudQuad(quad);

		/**
		 * Textura
		 */
		TextureState ts = TextureFactory.getInstance().createTextureState(
				hudDefinition.getTextura());
		ts.setEnabled(true);

		Vector2f uv1 = hudDefinition.getUv1();
		Vector2f uv2 = hudDefinition.getUv2();

		Vector2f[] textura = new Vector2f[] { new Vector2f(uv1.x, uv1.y),
				new Vector2f(uv1.x, uv2.y), new Vector2f(uv2.x, uv2.y),
				new Vector2f(uv2.x, uv1.y) };
		quad.setTextureCoords(new TexCoords(BufferUtils.createFloatBuffer(textura)));
		quad.setRenderState(ts);

		quad.updateRenderState();

		/**
		 * Alpha
		 */
		BlendState bs = DisplaySystem.getDisplaySystem().getRenderer().createBlendState();
		bs.setBlendEnabled(true);
		
		bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
        bs.setTestEnabled(true);
        bs.setTestFunction(BlendState.TestFunction.GreaterThan);
        bs.setEnabled(true);
        quad.setRenderState(bs);
        
		quad.updateRenderState();

		/**
		 * Posicionar
		 */
		quad.setLocalTranslation(width / 2, height / 2, 0);
	}

	public abstract void enhanceHud(HudDefinition hudDefinition);
}
